package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessagesService {

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    //添加联系人
    public void contacts(Long friendId) {
        //1、保存到mongodb数据库中：Friend
        friendApi.save(UserHolder.getUserId(),friendId);
        //2、将好友关系记录到环信
        huanXinTemplate.addContact("hx"+UserHolder.getUserId(),
                "hx"+friendId);
    }

    //查询好友列表
    public PageResult findFriends(Integer page, Integer pagesize) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //调用API查询 --->   List<Firend>   userid 和  frienid
        List<Friend> list = friendApi.findAll(userId,page,pagesize);
        //判断
        if(list == null || list.size()<=0) {
            return new PageResult();
        }
        //ContractVo ---> 将Firend转化为vo对象
        List<Long> ids = CollUtil.getFieldValues(list, "friendId", Long.class);  //null
        //批量查询用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        //转化
        List<ContactVo> vos = new ArrayList<>();
        for (Friend friend : list) {
            Long friendId = friend.getFriendId();
            UserInfo userInfo = map.get(friendId);
            ContactVo vo = ContactVo.init(userInfo);
            vos.add(vo);
        }
        return new PageResult(page,pagesize,0l,vos);
    }

    //根据环信id，查询用户数据
    public UserInfoVo findUserInfo(String huanxinId) {
        //huanxinId ：hx106
        String str = huanxinId.replaceAll("HX", "");
        //转化为long的id
        Long userId = Long.valueOf(str);
        //调用api查询用户详情
        UserInfo userInfo = userInfoApi.findById(userId);

        //构造vo
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo); //将userInfo中同名，同类型的属性，复制到vo对象中
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }
}
